<?php 	
/**
 * 神器
 */  
class shenqi {
	public function getIndex($param){
		$retVal = Session::init();
	    if (!$retVal) {
	        Output::instance()->resultCode(code_access_denied);
	        return;
	    }
	    $userName=Session::$user['userName'];
	    $customerId = Session::$user['customerId'];
	    Session::switchCustomer(0);
		$miUserShareModel = M("miuser_share");
		$miAllUserModel=M("all_user");
		$MiQuanUserModel=M("quan_user");
		Session::switchCustomer($customerId);
	    $uid = Session::$user['uid'];
	    $qId=$param->qId;
	    if($param->fromUId){
	    	$uid=$fromUId;
	    }
	    if(!$qId) {
	    	$quanList=$MiQuanUserModel->where("uid=$uid")->find();
	    	if($quanList) {
	    		$qId=$quanList["qid"];
	    	}
	    }
	    $result=$MiQuanUserModel->alias("a")
	    ->join("inner join wx_all_user b on a.uid=b.id ")
	    ->join("wx_".$customerId."_user_weixin_info c on c.id=b.weixinUserId")
	    ->where("a.qid=$qId and a.uid=$uid")
	    ->field("a.*,round(a.totalRedAmount,2) as totalRedAmount,c.nickname,c.headimgurl")
	    ->find();

	    $where["a.deleted"]=array('eq',0);
	    $where["a.uId"]=array('eq',$uid);
	    $where["a.qId"]=array('eq',$qId);
	    $list=$miUserShareModel->alias("a")
	    ->field("a.*,round(a.total,0) as total,round((a.total-a.overtotal),2) as stotal,round(a.rolltotal,2) as rolltotal")
	    ->order("a.createTime desc")
	    ->where($where)
	    ->select();

	    foreach ($list as $key => $value) {
			$list[$key]["date"]=format_date(strtotime($value["createTime"]));
		}
		$result["qId"]=$qId;
    	$result["list"]=$list;
    	$result["fromUId"]=$fromUId;
    	Output::instance()->module('shenqi',"index")->object($result);
	}
	public function getSend($param){
	    $retVal = Session::init();
	    if (!$retVal) {
	        Output::instance()->resultCode(code_access_denied);
	        return;
	    }
	    $userName=Session::$user['userName'];
	    $customerId = Session::$user['customerId'];
	    $uid = Session::$user['uid'];
	    $result["qId"]=$param->qId;
	    Output::instance()->module('shenqi',"list")->object($result);
	}
	/**
	 * [getAccoutMsg 计算账户充值情况]
	 * @param  [type] $param [description]
	 * @return [type]        [description]
	 */
	public function getAccoutList($param){
		$retVal = Session::init();
	    if (!$retVal) {
	        Output::instance()->resultCode(code_access_denied);
	        return;
	    }
	    $userName=Session::$user['userName'];
	    $customerId = Session::$user['customerId'];
	    $uid = Session::$user['uid'];
	    $qId=$param->qId;
	    Session::switchCustomer(0);
		$MiQuanUserModel = M("quan_user");
		Session::switchCustomer($customerId);
		$QuanResult=$MiQuanUserModel->where("qid=$qId and uid=$uid")->find();
		$arrAccount=array(
			1,5,10,20,50,100
		);
		$newarr=array();
		if($QuanResult) {
			$miCoins=$QuanResult["miCoins"];
			if(!$miCoins) {
				$miCoins=0;
			}
			foreach ($arrAccount as $key => $value) {
				$item=new stdClass();
				$item->base=round($value,2);
				if($miCoins < $value) {
					$rechange=floatval($value-$miCoins);
					$rechangepda=$rechange*0.05;
					$rechangetotal=$rechange+$rechangepda;
					$item->require=round($rechange,2);
					$item->pdage=round($rechangepda,2);
					$item->rechange=round($rechange,2);
					$item->rechangetotal=round($rechangetotal,2);
				}
				array_push($newarr, $item);
			}
		}
		$out=new stdClass();
		$out->miCoins=round($miCoins,2);	
		$out->list=$newarr;
	    Output::instance()->object($out);
	}
	/**
	 * [saveShare 保存分享]
	 * @param  [type] $param [description]
	 * @return [type]        [description]
	 */
	public function saveShare($param) {
		$retVal = Session::init();
	    if (!$retVal) {
	        Output::instance()->resultCode(code_access_denied);
	        return;
	    }
	    $userName=Session::$user['userName'];
	    $customerId = Session::$user['customerId'];
	    $uid = Session::$user['uid'];
	    $qId=$param->qId;
	    Session::switchCustomer(0);
		$MiUserShareModel = M("miuser_share");
		$MiQuanUserModel = M("quan_user");
		$miAccountModel = M("miaccount_friend");
		$shareBaseModel=M("mishare");
		$shareMaterModel=M("mishare_material");
		$recommentModel=M("mirecomment");
		Session::switchCustomer($customerId);
		$time=date("Y-m-d H:i:s");
		$isRed=$param->isRed;
		$total=0;
		$out=new stdClass();
		if($isRed) {
			$total=$param->total;
			$quanUser=$MiQuanUserModel->where("uid=$uid and qid=$qId")->find();
			if($quanUser) {
				$miCoins=$quanUser["miCoins"];
				if(!$miCoins) {
					$miCoins=0;
				}
				if($miCoins < $total) {
					$out->msg="账户余额不足，请先充值！";
					$out->code=1;
					Output::instance()->object($out);
					return;
				}
			}
		}
		$title=$param->title;
		$content=$param->content;
		$pics=$param->pics;
		$jsonPic=json_decode($pics,true);

		$addData=array(
			"title"=>$title,
			"content"=>$content,
			"pics"=>$pics,
			"uId"=>$uid,
			"qId"=>$qId,
			"isRed"=>$isRed,
			"total"=>$total,
			"status"=>0,
			"overtotal"=>$total,
			"createTime"=>$time,
			"updateTime"=>$time,
			"deleted"=>0
		);
		$MiUserShareModel->startTrans();
		$moduleId=$MiUserShareModel->add($addData);
		if($moduleId===false) {
			$MiUserShareModel->rollback();
			Output::instance()->resultCode(code_sql_error);
			return;
		}
		//分享基础表
		$shareBaseData=array(
			"module" => "shenqi" ,
			"moduleId" => $moduleId ,
			"shareCount" => 0 ,
			"viewCount" => 0 ,
			"praiseCount" => 0 , 
			"commentCount" => 0 , 
			"createTime"=> $time,
			"deleted" => 0 
		);
		//分享素材表
		if(count($jsonPic) > 0) {
			$shareImgs=$jsonPic[0]["picUrl"];
		}
		$shareMaterData=array(
			"title" => $title,
			"shareImg" => $shareImgs,
			"shareImg1" => $pics,
			"description" => $content,
			"deleted"=>0
		);
		$sId=$shareBaseModel->add($shareBaseData);
		if($sId===false) {
			$MiUserShareModel->rollback();
			Output::instance()->resultCode(code_sql_error);
			return;
		}
		//添加素材表
		if($sId ) {
			$shareMaterData["sId"]=$sId;
			$mSId=$shareMaterModel->add($shareMaterData);
		}
		if($mSId===false) {
			$MiUserShareModel->rollback();
			Output::instance()->resultCode(code_sql_error);
			return;
		}
		//分享保存到个人推荐中
		$addData=array(
			"uId"=>$uid,
			"quanId"=>$qId,
			"sId"=>$sId,
			"createTime"=>date("Y-m-d H:i:s"),
			"deleted"=>0
		);
		$recomment=$recommentModel->add($addData);
		if($recomment===false) {
			$MiUserShareModel->rollback();
			Output::instance()->resultCode(code_sql_error);
			return;
		}
		if($isRed) {
			//扣除账户余额添加红包记录
			$success2=$MiUserShareModel->query("update wx_quan_user set miCoins=miCoins-".$total." where uid=$uid and qid=$qId");
			if($success2===false) {
				$MiUserShareModel->rollback();
				Output::instance()->resultCode(code_sql_error);
				return;
			}
			//添加支出记录
			$addData1=array(
				"module"=>"shenqi",
				"moduleId"=>$moduleId,
				"uId"=>$uid,
				"quanId"=>$qId,
				"vId"=>0,
				"description"=>$param->title."分享红包支出",
				"sId"=>0,
				"vsistId"=>0,
				"money"=>$total,
				"type"=>1,
				"createTime"=>date("Y-m-d H:i:s"),
				"deleted"=>0
			);
			$success3=$miAccountModel->add($addData1);
			if($success3===false) {
				$MiUserShareModel->rollback();
				Output::instance()->resultCode(code_sql_error);
				return;
			}
		} else {
			$success2=true;
			$success3=true;
		}
		
		$MiUserShareModel->commit();
		$out->id=$moduleId;
		$out->code=0;
		Output::instance()->object($out);
	}
	public function createRechangeOrder($param){
		$retVal = Session::init();
	    if (!$retVal) {
	        Output::instance()->resultCode(code_access_denied);
	        return;
	    }
	    $userName=Session::$user['userName'];
	    $customerId = Session::$user['customerId'];
	    $uid = Session::$user['uid'];
	    $qId=$param->qId;
	    Session::switchCustomer(0);
		$miOrderModel = M("miuser_recharge_order");
		Session::switchCustomer($customerId);
		$time=date("Y-m-d H:i:s");
		$price=$param->price;
		$rechangepda=$price*0.05;
		$rechangetotal=round(($price+$rechangepda),2);
		//账户充值
		$addData=array(
			"qId"=>$qId,
			"price"=>$price,
			"totalprice"=>$rechangetotal,
			"pda"=>$rechangepda,
			"uId"=>$uid,
			"status"=>0,
			"deleted"=>0,
			"type"=>0,
			"createTime"=>date("Y-m-d H:i:s"),
			"updateTime"=>date("Y-m-d H:i:s")
		);
		$success=$miOrderModel->add($addData);
		if($success) {
			 $out=new stdClass();
			 $out->id=$success;
			 $out->code=0;
			 $out->price=$rechangetotal;
			 Output::instance()->object($out);
		} else {
			Output::instance()->object(code_sql_error);
		}
	}
	public function saveAccountFree($oid){
	    $userName=Session::$user['userName'];
	    $customerId = Session::$user['customerId'];
	    $qId=$param->qId;
	    Session::switchCustomer(0);
		$miAccountModel = M("miaccount_friend");
		$miOrderModel = M("miuser_recharge_order");
		Session::switchCustomer($customerId);
		$time=date("Y-m-d H:i:s");
		//账户充值
		$order=$miOrderModel->where("id=$oid")->find();
		if(!$order) {
			Output::instance()->resultCode(1,"订单不存在");
			return;
		}
		$price=$order["price"];
		$qId=$order["qId"];
		$uid =$order['uId'];

	    $miAccountModel->startTrans();
		
		$success1=$miOrderModel->query("update wx_quan_user set miCoins=miCoins+".$price." where uid=$uid and qid=$qId");
		if($success1===false) {
			$miAccountModel->rollback();
			Output::instance()->object(code_sql_error);
		}
		$success2=$miOrderModel->query("update wx_miuser_recharge_order set status=1 where id=$oid");
		if($success2===false) {
			$miAccountModel->rollback();
			Output::instance()->object(code_sql_error);
		}
		$addData=array(
			"module"=>"shenqi",
			"moduleId"=>"0",
			"uId"=>$uid,
			"quanId"=>$qId,
			"vId"=>0,
			"description"=>"账户充值",
			"sId"=>0,
			"vsistId"=>0,
			"money"=>$price,
			"type"=>0,
			"createTime"=>date("Y-m-d H:i:s"),
			"deleted"=>0
		);
		$success3=$miAccountModel->add($addData);
		if($success3===false) {
			$miAccountModel->rollback();
			Output::instance()->object(code_sql_error);
		}
		$miAccountModel->commit();
		Output::instance()->object(code_success);
	}
	public function getView($param){
		$retVal = Session::init();
	    if (!$retVal) {
	        Output::instance()->resultCode(code_access_denied);
	        return;
	    }
	    $userName=Session::$user['userName'];
	    $customerId = Session::$user['customerId'];
	    Session::switchCustomer(0);
		$miUserShareModel = M("miuser_share");
		$miUserRedModel = M("miusershare_getred");
		$miAllUserModel=M("all_user");
		$MiQuanUserModel=M("quan_user");
		Session::switchCustomer($customerId);
	    $uid = Session::$user['uid'];
	    $id=$param->id;
	    $qId=$param->qId;
	    $result=$miUserShareModel->alias("a")
	    ->join("inner join wx_all_user b on a.uId=b.id")
	    ->join("inner join wx_".$customerId."_user_weixin_info c on c.id=b.weixinUserId")
	    ->join("wx_mishare s on s.moduleId=a.id")
	    ->field("a.*,c.nickname,c.headimgurl,s.id as sId")
	    ->where("a.id=$id and a.deleted=0 and s.module='shenqi'")->find();
	    $result["isCanShare"]=1;
	    $fromUId=$param->fromUId;
	    if($result["uId"]!=$uid) { //分享进来的
	    	$result["isCanShare"]=0;
	    	$miUid=$fromUId;
	    } else {
	    	$miUid=$uid;
	    }
	    if(!isMicroMessengerUserAgent()){
	    	$result["status"]=2;
	    }
	   	$pics=json_decode($result["pics"],true);
	    $result["pics"]=$pics;
	    $desc=preg_replace("/\n/","", $result["content"]);
	    $content=preg_replace("/\n/","<br/>", $result["content"]);
	    $result["desc"]=addslashes($desc);
	    $result["title"]=addslashes($result["title"]);
	    $result["content"]=addslashes($content);
	    $result["isPic"] =count($pics);

	    if(!$result) {
	    	Output::instance()->resultCode(0,"该分享已经被删除！");
	    	return;
	    }
	    $quanUser=$MiQuanUserModel->where("uid=$uid")->find();
	    if(!$quanUser) {
	    	$result["isCanShare"]=0;
	    }
	    $result["hasImg"]=0;
	    if(count($pics)>0) {
    		$result["hasImg"]=1;
    	}
	    if($result["isRed"]){
	    	$result["shareImg"]="http://oss.mboxone.com/20150714/image/3/1436872639372138.png";
	    } else {
	    	if(count($pics)>0) {
		    	$result["shareImg"]=$pics[0]["picUrl"];
		    } else {
		    	$userInfo=$miAllUserModel->alias("a")->join("wx_".$customerId."_user_weixin_info b on a.weixinUserId=b.id")
		    	->field("b.headimgurl")
		    	->where("a.id=$miUid")->find();
		    	if($userInfo) {
		    		$result["shareImg"]=$userInfo["headimgurl"];
		    	}
		    }
	    }
	    $redResult=$miUserRedModel->where("usId=$id and uId=$uid")->find();
	    if($redResult) {
	    	$result["isGetRed"]=1;
	    } else {
	    	$result["isGetRed"]=0;
	    }
	    //添加访问记录
		$Guid = new Guid();   
		$guid = $Guid->toString();
		$visitParam=new StdClass();
		$visitParam->guid=$guid;
		$visitParam->sId=$result["sId"];
		$visitParam->fromGuid=$param->fromGuid;
		$visitParam->miUId=$miUid;
		$visitParam->qId=$qId;
		$visitParam->fromPage="shenqi_getView";
		$visitId = Module::callModule("quan", Session::$user,"addVisit", $visitParam);

    	$result["qId"]=$qId;
	    $result["id"]=$id;
	    $result["guid"]=$guid;
	    $result["fromUId"]=$miUid;
	    Output::instance()->module('shenqi',"artifact")->object($result);
	}
	public function getRedUserList($param){
		$retVal = Session::init();
	    if (!$retVal) {
	        Output::instance()->resultCode(code_access_denied);
	        return;
	    }
	    $userName=Session::$user['userName'];
	    $customerId = Session::$user['customerId'];
	    Session::switchCustomer(0);
		$miUserRedModel = M("miusershare_getred");
		Session::switchCustomer($customerId);
	    $uid = Session::$user['uid'];
	    $id=$param->id;
	    $qId=$param->qId;
	    $count=$miUserRedModel->where("usId=$id")->count();
	    $list=$miUserRedModel->alias("a")
	    ->join("inner join wx_all_user b on a.uId=b.id ")
	    ->join("inner join wx_".$customerId."_user_weixin_info c on c.id=b.weixinUserId")
	    ->field("a.*,c.nickname,c.headimgurl")
	    ->where("usId=$id")
	    ->limit("0,24")
	    ->order("id asc")
	    ->select();

    	$result["count"]=$count;
    	$out=new stdClass();
    	$out->count=$count;
    	
    	if($list) {
    		$out->list=$list;
    	} else {
    		$out->list=array();
    	}
	    Output::instance()->object($out);
	}
	function randomFloat($min = 0, $max = 1) { 
		$num=$min + mt_rand() / mt_getrandmax() * ($max - $min); 
		return round($num,2); 
	}
	/**
	 * [getRed 拆红包的]
	 * @param  [type] $param [description]
	 * @return [type]        [description]
	 */
	public function getRed($param){
		$retVal = Session::init();
	    if (!$retVal) {
	        Output::instance()->resultCode(code_access_denied);
	        return;
	    }
	    $userName=Session::$user['userName'];
	    $customerId = Session::$user['customerId'];
	    Session::switchCustomer(0);
		$miUserShareModel = M("miuser_share");
		$miUserRedModel = M("miusershare_getred");
		Session::switchCustomer($customerId);
	    $uid = Session::$user['uid'];
	    $id=$param->id;
	    $result=$miUserShareModel->alias("a")
	    ->join("wx_all_user b on a.uId=b.id")
	    ->join("wx_".$customerId."_user_weixin_info c on c.id=b.weixinUserId")
	    ->field("a.*,c.nickname")
	    ->lock(true)->where("a.id=$id")->find();
	    if(!$result) {
	    	Output::instance()->module('shenqi',"artifact")->resultCode(0,"不存在");
	    	return;
	    }
	    $out=new stdClass();
	    $redResult=$miUserRedModel->where("usId=$id and uId=$uid")->find();
	    if($redResult) {
	    	$out->code=1;
	    	$out->msg="您已经领过他的红包了";
	    	Output::instance()->object($out);
	    	return;
	    }
	    $total=$result["total"];
	    $overtotal=$result["overtotal"];
	    $miUid=$result["uId"];
	    $qId=$result["qId"];

	    if($result["status"] > 0 || $overtotal <=0) { //剩余金额不够领了
	    	$out->code=2;
	    	$out->msg="红包被抢完了";
	    	Output::instance()->object($out);
	    	return;
	    }
	    $rands = rand(1,10);
	    if($rands <=9) {
	    	$amount=self::randomFloat(0.05,0.2);//随机的红包金额
	    } else {
	    	$amount=self::randomFloat(0.2,1);//随机的红包金额
	    }
	    if($overtotal < 0.1 || $amount > $overtotal) { //随机金额不够领取
	    	$amount=$overtotal;
	    }
	    $time=date("Y-m-d H:i:s");
	    $addData=array(
	    	"usId"=>$id,
	    	"uId"=>$uid,
	    	"money"=>$amount,
	    	"createTime"=>$time,
	    	"updateTime"=>$time
	    );
	    $miUserRedModel->startTrans();
	    $addid=$miUserRedModel->add($addData);

	    if($overtotal > $amount) {
	    	$sqlstr="update wx_miuser_share set overtotal=overtotal-".$amount." where id=$id";
	    } else {
	    	$sqlstr="update wx_miuser_share set overtotal=0,status=1 where id=$id";
	    }
	    $success1=$miUserRedModel->query($sqlstr);
	    Log::write("红包金额".$amount);
	    //更新密友总红包记录
	    $success2=$miUserRedModel->lock(true)->query("update wx_quan_user set totalRedAmount=totalRedAmount+".$amount." where uid=$miUid and qid=$qId");
	    //调用企业微信转账，发红包
	    $success3=WeixinApi::transferAccountsByOpenId($userName,$amount,$result["nickname"]."的红包");
	    //$success3=true;
	    if($addid!==false && $success1!==false && $success2!==false && $success3!==false) {
	    	$out=new stdClass();
	    	$out->code=0;
	    	$out->amount=$amount;
	    	$miUserRedModel->commit();
	    	Output::instance()->object($out);
	    } else {
	    	$out->code=3;
	    	$out->msg="系统错误";
	    	$miUserRedModel->rollback();
	    	Output::instance()->object($out);
	    }
	}
	/**
	 * [deleteShare 删除一个分享]
	 * @param  [type] $param [description]
	 * @return [type]        [description]
	 */
	public function deleteShare($param){
		$retVal = Session::init();
	    if (!$retVal) {
	        Output::instance()->resultCode(code_access_denied);
	        return;
	    }
	    $userName=Session::$user['userName'];
	    $customerId = Session::$user['customerId'];
	    Session::switchCustomer(0);
		$MiUserShareModel = M("miuser_share");
		$shareBaseModel=M("mishare");
		$shareMaterModel=M("mishare_material");
		Session::switchCustomer($customerId);
	    $uid = Session::$user['uid'];
	    $id=$param->id;
	    $upData["deleted"]=1;
	    $MiUserShareModel->startTrans();
	    $success1=$MiUserShareModel->where("id=$id")->save($upData);
	    if($success1===false){
	    	$MiUserShareModel->rollback();
	    	Output::instance()->resultCode(code_sql_error);
	    }
	    $success2=R("MiYouQuan/rollbackAccount",array($id));
	    if($success2===false){
	    	$MiUserShareModel->rollback();
	    	Output::instance()->resultCode(code_sql_error);
	    }
	    $wheres["moduleId"]=$id;
	    $wheres["module"]="shenqi";
	    $shareRs=$shareBaseModel->where($wheres)->find();
	    if($shareRs) {
	    	$sId=$shareRs["id"];
	    }
	    $success3=$shareBaseModel->where($wheres)->delete();
	    if($success3===false){
	    	$MiUserShareModel->rollback();
	    	Output::instance()->resultCode(code_sql_error);
	    }
	    $wheres1["sId"]=$sId;
	    $success4=$shareMaterModel->where($wheres1)->delete();
	    if($success4===false){
	    	$MiUserShareModel->rollback();
	    	Output::instance()->resultCode(code_sql_error);
	    }
	    $MiUserShareModel->commit();
	    Output::instance()->resultCode(code_success);
	}
	/**
	 * [getObjectDetail 获取内容详情页面]
	 * @param  [type] $id [description]
	 * @return [type]     [description]
	 */
	public function getObjectDetail($param){
		$retVal = Session::init();
	    if (!$retVal) {
	        Output::instance()->resultCode(code_access_denied);
	        return;
	    }
		$customerId = Session::$user["customerId"];
		$uid = Session::$user["uid"];
		Session::switchCustomer(0);
		$ShareModel = M("miuser_share");
		Session::switchCustomer($customerId);
		$id=$param->id;
		$fromGuid=$param->fromGuid;
		if(!$fromGuid){
			$fromGuid="";
		}
		if($param->fromUId){
			$fromUId=$param->fromUId;
		}
		if($param->miUId){
			$fromUId=$param->miUId;
		}
		$p=new stdClass();
		$p->miUId=$fromUId;
		$p->fromGuid=$fromGuid;
		$p->qId=$param->qId;
		$p->fromUId=$fromUId;
		$p->id=$id;
		$p=urlencode(json_encode($p));
		$detailUrl=C('SERVER_HOST') . "call.html?customerId=$customerId&module=shenqi&method=getView&params=$p";
		$result["detailUrl"]=$detailUrl;
		return $result;
	}
}